﻿'    This file is part of Open Subtitle Editor.
'
'    Open Subtitle Editor is free software: you can redistribute it and/or modify
'    it under the terms of the GNU General Public License as published by
'    the Free Software Foundation, either version 3 of the License, or
'    (at your option) any later version.
'
'    Open Subtitle Editor is distributed in the hope that it will be useful,
'    but WITHOUT ANY WARRANTY; without even the implied warranty of
'    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
'    GNU General Public License for more details.
'
'    You should have received a copy of the GNU General Public License
'    along with Open Subtitle Editor.  If not, see <http://www.gnu.org/licenses/>.

Public Class frmTranslator

    Private fileReader As System.IO.StreamReader
    Private fileWriter As System.IO.StreamWriter
    Private currentLine As String
    Private currentData() As String
    Private currentName As String
    Private folderDialog As New FolderBrowserDialog

    Private Sub frmTranslator_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles MyBase.Load

        If AlreadyRunning() = True Then
            MsgBox("The Interface Translator for Open Subtitle Editor is already running. If the problem persists, try logging off your user account and logging back on.", MsgBoxStyle.Exclamation)
            End
        End If

        With folderDialog
            ' Desktop is the root folder in the dialog.
            .RootFolder = Environment.SpecialFolder.Desktop
            ' Select the C:\Windows directory on entry.
            If My.Computer.FileSystem.DirectoryExists(Application.StartupPath & "\source") Then
                .SelectedPath = Application.StartupPath & "\source"
            Else
                .SelectedPath = Application.StartupPath
            End If

            ' Prompt the user with a custom message.
            .Description = "Select the ""source"" or ""Languages"" directory"

            If .ShowDialog = DialogResult.Cancel Then
                End
            End If
        End With

        Try
            ' IMPORTANT DEBUGGING INFORMATION: Check for source files suceeds only if the folder selected
            ' is the one containing the whole solution.
            fileReader = My.Computer.FileSystem.OpenTextFileReader(folderDialog.SelectedPath & "\SubtitleEditor\Dialogs\frmMain.vb")

            LoadFromSource()
        Catch ex As Exception
            TryLanguage()
        End Try

    End Sub

    Private Sub LoadFromSource()
        ReadStrings()

        fileReader = My.Computer.FileSystem.OpenTextFileReader(folderDialog.SelectedPath & "\SubtitleEditor\Dialogs\frmPreviewSettings.vb")

        ReadStrings()

        fileReader = My.Computer.FileSystem.OpenTextFileReader(folderDialog.SelectedPath & "\SubtitleEditor\Modules\Generic.vb")

        ReadStrings()

        fileReader = My.Computer.FileSystem.OpenTextFileReader(folderDialog.SelectedPath & "\SubtitleEditor\Modules\Subtitles.vb")

        ReadStrings()

        fileReader = My.Computer.FileSystem.OpenTextFileReader(folderDialog.SelectedPath & "\SubtitleEditor\Dialogs\frmAbout.vb")

        ReadStrings()

        fileReader = My.Computer.FileSystem.OpenTextFileReader(folderDialog.SelectedPath & "\SubtitleEditor\Dialogs\frmLicense.vb")

        ReadStrings()

        fileReader = My.Computer.FileSystem.OpenTextFileReader(folderDialog.SelectedPath & "\SubtitleEditor\Dialogs\frmUnknownFormat.vb")

        ReadStrings()

        fileReader.Close()

        dgvLines.Sort(dgvLines.Columns.Item(0), System.ComponentModel.ListSortDirection.Ascending)

        Dim Repeat As Boolean
        Dim first, second As String
here:
        For i = 0 To dgvLines.RowCount - 1
            If i >= dgvLines.RowCount - 1 Then Exit For
            first = dgvLines.Rows.Item(i).Cells.Item(0).Value
            second = dgvLines.Rows.Item(i + 1).Cells.Item(0).Value
            If first = second Then
                dgvLines.Rows.Remove(dgvLines.Rows.Item(i + 1))
            End If
        Next

        Repeat = False
        For i = 0 To dgvLines.RowCount - 1
            If i >= dgvLines.RowCount - 1 Then Exit For
            first = dgvLines.Rows.Item(i).Cells.Item(0).Value
            second = dgvLines.Rows.Item(i + 1).Cells.Item(0).Value
            If first = second Then
                Repeat = True
                Exit For
            End If
        Next

        If Repeat = True Then GoTo here

        For i = dgvLines.RowCount - 1 To 0 Step -1
            first = dgvLines.Rows.Item(i).Cells.Item(0).Value
            If first = "yVal text As Strin" Then
                dgvLines.Rows.RemoveAt(i)
            End If
        Next

    End Sub

    Private Sub TryLanguage()

        Try
            fileReader = My.Computer.FileSystem.OpenTextFileReader(folderDialog.SelectedPath & "\English.sel")
        Catch ex As Exception
            End
        End Try

        If Not fileReader.ReadLine = "! Actual Open Subtitle Editor Language File" Then
            MsgBox("The English language file is corrupted. Please re-install the program, and if the problem persists contact the project administrator.")
            Exit Sub
        End If

        Dim currentLine As String
        Dim currentFields(2) As String
        While Not fileReader.EndOfStream
            currentLine = fileReader.ReadLine
            If Not currentLine = "" And Not Microsoft.VisualBasic.Left(currentLine, 1) = "!" Then
                currentFields = Split(currentLine, ",", "2")
                dgvLines.Rows.Add(currentFields(0), LTrim(currentFields(1)))
            End If
        End While

        fileReader.Close()

    End Sub

    Private Sub OpenOriginalToolStripMenuItem_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles OpenOriginalToolStripMenuItem.Click
        dlgOpen.Filter = "Language File (*.sel)|*.sel"
        dlgOpen.InitialDirectory = Application.StartupPath & "\Languages"
        dlgOpen.FileName = ""
        If dlgOpen.ShowDialog() = Windows.Forms.DialogResult.OK Then
            fileReader = My.Computer.FileSystem.OpenTextFileReader(dlgOpen.FileName)
            If Not fileReader.ReadLine = "! Actual Open Subtitle Editor Language File" Then
                MsgBox("File selected was not a Subtitle Editor language file.")
                Exit Sub
            End If
        Else
            Exit Sub
        End If

        For Each row As DataGridViewRow In dgvLines.Rows
            row.Cells(1).Value = ""
        Next

        Dim currentLine As String
        Dim currentFields(2) As String
        While Not fileReader.EndOfStream
            currentLine = fileReader.ReadLine
            If Not currentLine = "" And Not Microsoft.VisualBasic.Left(currentLine, 1) = "!" Then
                currentFields = Split(currentLine, ",", "2")
                For i = 0 To dgvLines.RowCount - 1
                    If currentFields(0) = CStr(dgvLines.Rows.Item(i).Cells.Item(0).Value) Then
                        dgvLines.Rows.Item(i).Cells.Item(1).Value = LTrim(currentFields(1))
                        Exit For
                    End If
                Next
            End If
        End While

        fileReader.Close()

    End Sub

    Private Sub OpenTranslationToolStripMenuItem_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles OpenTranslationToolStripMenuItem.Click
        dlgOpen.Filter = "Language File (*.sel)|*.sel"
        dlgOpen.InitialDirectory = Application.StartupPath & "\Languages"
        dlgOpen.FileName = ""
        If dlgOpen.ShowDialog() = Windows.Forms.DialogResult.OK Then
            fileReader = My.Computer.FileSystem.OpenTextFileReader(dlgOpen.FileName)
            If Not fileReader.ReadLine = "! Actual Open Subtitle Editor Language File" Then
                MsgBox("File selected was not a Subtitle Editor language file, resetting to English.")
                Exit Sub
            End If
        Else
            Exit Sub
        End If

        For Each row As DataGridViewRow In dgvLines.Rows
            row.Cells(2).Value = ""
        Next

        Dim currentLine As String
        Dim currentFields(2) As String
        While Not fileReader.EndOfStream
            currentLine = fileReader.ReadLine
            If Not currentLine = "" And Not Microsoft.VisualBasic.Left(currentLine, 1) = "!" Then
                currentFields = Split(currentLine, ",", "2")
                For i = 0 To dgvLines.RowCount - 1
                    If currentFields(0) = CStr(dgvLines.Rows.Item(i).Cells.Item(0).Value) Then
                        dgvLines.Rows.Item(i).Cells.Item(2).Value = LTrim(currentFields(1))
                        Exit For
                    End If
                Next
            End If
        End While

        fileReader.Close()

        checkIfComplete()

    End Sub

    Private Sub SaveTranslationToolStripMenuItem_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles SaveTranslationToolStripMenuItem.Click
        dlgSave.Filter = dlgOpen.Filter
        dlgSave.InitialDirectory = dlgOpen.InitialDirectory
        If dlgSave.ShowDialog = Windows.Forms.DialogResult.OK Then
            fileWriter = My.Computer.FileSystem.OpenTextFileWriter(dlgSave.FileName, False)

            fileWriter.WriteLine("! Actual Open Subtitle Editor Language File")
            For i = 0 To dgvLines.RowCount - 1
                If Not dgvLines.Rows.Item(i).Cells.Item(2).Value = "" Then
                    fileWriter.WriteLine(dgvLines.Rows.Item(i).Cells.Item(0).Value & ", " & dgvLines.Rows.Item(i).Cells.Item(2).Value)
                End If
            Next
            fileWriter.Close()
        End If
    End Sub

    ' Return True if another instance
    ' of this program is already running.
    Public Function AlreadyRunning() As Boolean
        ' Get our process name.
        Dim my_proc As Process = Process.GetCurrentProcess
        Dim my_name As String = my_proc.ProcessName

        ' Get information about processes with this name.
        Dim procs() As Process = _
            Process.GetProcessesByName(my_name)

        ' If there is only one, it's us.
        If procs.Length = 1 Then Return False

        ' If there is more than one process,
        ' see if one has a StartTime before ours.
        Dim i As Integer
        For i = 0 To procs.Length - 1
            If procs(i).StartTime < my_proc.StartTime Then _
                Return True
        Next i

        ' If we get here, we were first.
        Return False
    End Function

    Public Sub ReadStrings()
        While Not fileReader.EndOfStream
            currentLine = fileReader.ReadLine
            currentData = Split(currentLine, "loadStringFromLangFile(")
            If currentData.Count = 2 Then
                currentData = Split(currentData(1), ")")
                currentName = Microsoft.VisualBasic.Mid(currentData(0), 2, currentData(0).Length - 2)
                dgvLines.Rows.Add(currentName, "", "")
            End If
        End While
    End Sub

    Private Sub checkIfComplete()
        Dim incomplete = False
        For Each row As DataGridViewRow In dgvLines.Rows
            If row.Cells(2).Value = "" Then
                incomplete = True
            End If
        Next

        If incomplete = True Then
            lblStatus.Text = "Current translation seems incomplete. (Double-click to go to first missing line.)"
            lblStatus.Font = New Font(lblStatus.Font, FontStyle.Bold)
            lblStatus.ForeColor = Color.Red
        Else
            lblStatus.Text = "Current translation seems complete."
            lblStatus.Font = New Font(lblStatus.Font, FontStyle.Regular)
            lblStatus.ForeColor = Color.Black
        End If
    End Sub

    Private Sub dgvLines_CellEndEdit(ByVal sender As Object, ByVal e As System.Windows.Forms.DataGridViewCellEventArgs) Handles dgvLines.CellEndEdit
        If dgvLines.SelectedCells(0).OwningColumn Is dgvLines.Columns(2) Then
            checkIfComplete()
        End If
    End Sub

    Private Sub StatusStrip1_DoubleClick(ByVal sender As Object, ByVal e As System.EventArgs) Handles StatusStrip1.DoubleClick
        If lblStatus.ForeColor = Color.Red Then
            For Each row As DataGridViewRow In dgvLines.Rows
                If row.Cells(2).Value = "" Then
                    For i = 0 To dgvLines.RowCount - 1
                        dgvLines.Rows(i).Selected = False
                    Next
                    row.Selected = True
                    scrollToSelectedRow()
                    Exit Sub
                End If
            Next
        End If
    End Sub

    Private Sub scrollToSelectedRow()
        Dim halfWay As Integer = (dgvLines.DisplayedRowCount(False) / 2)
        If dgvLines.FirstDisplayedScrollingRowIndex + halfWay > dgvLines.SelectedRows(0).Index Or (dgvLines.FirstDisplayedScrollingRowIndex + dgvLines.DisplayedRowCount(False) - halfWay) <= dgvLines.SelectedRows(0).Index Then

            Dim targetRow As Integer = dgvLines.SelectedRows(0).Index

            targetRow = Math.Max(targetRow - halfWay, 0)
            dgvLines.FirstDisplayedScrollingRowIndex = targetRow

        End If
    End Sub

End Class
